from   flaskr_config import app
from   flask         import Flask , request , session , g , redirect , \
                            url_for , abort , render_template , flash
import sqlite3

execfile(app.root_path + '/constants.py')


## db ##

def connect_db():
  db             = sqlite3.connect(app.config[DB_KEY])
  db.row_factory = sqlite3.Row

  return db

def get_db():
  if not hasattr(g , DB_ATTR):
    g.sqlite_db = connect_db()

  return g.sqlite_db

def init_db():
  db = get_db()
  with app.open_resource(DB_SCHEMA_FILE , mode = 'r') as sql_file:
    db.cursor().executescript(sql_file.read())
  db.commit()

@app.cli.command(INIT_DB_CMD)
def initdb_command():
  init_db()
  print(INIT_DB_MSG)

@app.teardown_appcontext
def close_db(error):
  if hasattr(g , DB_ATTR):
    g.sqlite_db.close()


## routes ##

@app.route(ROOT_ROUTE)
def show_entries():
  db      = get_db()
  cur     = db.execute(FETCH_ENTRIES_SQL)
  entries = cur.fetchall()

  return render_template(HOME_PAGE , entries = entries)

@app.route(ADD_ROUTE , methods = [POST_METHOD])
def add_entry():
  if not session.get(IS_AUTHED_KEY):
    abort(UNAUTH_STATUS)

  db    = get_db()
  title = request.form[TITLE_CSS]
  text  = request.form[TEXT_CSS]
  db.execute(ADD_ENTRY_SQL , [title , text])
  db.commit()
  flash(ADDED_MSG)

  return redirect(url_for(HOME_PAGE_KEY))

@app.route(LOGIN_ROUTE , methods = [GET_METHOD , POST_METHOD])
def login():
  error = None
  if request.method == POST_METHOD:
    if request.form[USERNAME_CSS] != app.config[USERNAME_KEY]:
      error = LOGIN_ERROR_MSG
    elif request.form[PASSWORD_CSS] != app.config[PASSWORD_KEY]:
      error = PASS_ERROR_MSG
    else:
      session[IS_AUTHED_KEY] = True
      flash(LOGIN_MSG)

      return redirect(url_for(HOME_PAGE_KEY))

  return render_template(LOGIN_PAGE , error = error)

@app.route(LOGOUT_ROUTE)
def logout():
  session.pop(IS_AUTHED_KEY , None)
  flash(LOGOUT_MSG)

  return redirect(url_for(HOME_PAGE_KEY))
